Skip to content

fix(bff): end a login whose IdP session got a back-channel logout before its row - #525

Merged
pdevito3 merged 4 commits into
mainfrom
fix/bff-logout-after-login
Nov 15, 2026
Merged

pdevito3 merged 4 commits into
mainfrom
fix/bff-logout-after-login

Conversation

@pdevito3

Copy link
Copy Markdown
Owner

Why

Stacked on #521.

A back-channel logout can come after the code exchange of a login and before the login writes its BFF session row. The logout then finds no row and answers 200, and the login creates a row that stays signed in. Now the record of the logout token ends that login.

What changed

  • The replay cache row keeps the sid, the sub, and the iat of the logout token. EfBffSessionStore.CreateAsync reads these records in the login transaction, and refuses a login of the same IdP session if a record has an iat at or after the iat of the ID token of the login, less 5 s for the clocks of the IdP.
  • IdpSessionLock takes pg_advisory_xact_lock on the sub and the sid of the login, and on the sid (or the sub) of the logout token. Thus each logout commits before the read of the login, or finds the row after the login commits.
  • LoginTimes puts a deadline in the protected state at the challenge: the challenge plus RemoteAuthenticationTimeout. A login at its deadline fails, and a logout record lives at least that long after its receipt, so the cleanup never deletes a record that a login in flight still needs. A refused login gets the 400 problem of a failed callback.

Scope

  • Covers the G1 finding of the bff-session-lifecycle model. The model, the spec, and the authentication doc describe the fix.
  • Leaves out a revoke of the refresh token of a refused login. With Keycloak, a revoke ends the client session of the sid, and another row of the same browser can have that sid.

Tradeoffs

  • The store throws LoginRefusedException, because ITicketStore.StoreAsync returns only a key. A middleware before UseAuthentication maps it to the 400. UseExceptionHandler would clear the deletes of the correlation and nonce cookies.
  • The match uses the iat of the ID token, not its auth_time. An SSO login keeps the auth_time of the first authentication. Keycloak sends a logout token for the sid when a user revokes the consent of the client, and keeps the SSO session. With auth_time, each SSO login after that failed until the record expired.
  • A logout token issued up to 5 s after the tokens of a new login of the same IdP session also ends that login. The times are whole seconds.
  • The rule trusts the IdP to issue no tokens of a session that it ended. Keycloak refuses the code exchange of an ended session, and Authentik deletes the codes of a session when the session ends. A provider that redeems such a code could let a login whose code came before the logout write a row. A second rule on the challenge time would close that case for all providers, but it compares the clocks of BFF instances and refuses each login for a short time after a consent revoke. Spec 3.1 states the precondition.

Blast Radius

Each login now runs one transaction with two advisory locks and one indexed read, and waits for a back-channel logout of its IdP session. A login that began before the deploy has no deadline in its state, so its callback gets 400 one time, and the user logs in again. The migration adds three columns and two indexes to used_logout_tokens. Its old rows have no sid or sub, so they end no login. Until each instance runs this code, an old instance writes the row of a login with no lock and no read of the records.

Verification

  • dotnet build FullstackTemplate.slnx has 0 warnings. tests/FullstackTemplate.Bff.Tests passes 541 of 541 in 4 of 4 runs.
  • The new tests fail before the fix: a logout of the sid or of the sub that comes during the held code exchange, and a login at its deadline, each got 302 where 400 was expected. The record lifetime test got an expiry before the receipt plus RemoteAuthenticationTimeout. With the lock removed, the test of a logout during the read of the records saw no lock wait, and left a readable row after the logout answered 200. With the auth_time window, the SSO login after a logout of its sid that the IdP kept got 400 where 302 was expected. An ID token with no readable iat (an encrypted token, or no claim) passed LoginTimes.Of and later failed with ArgumentOutOfRangeException. It now fails there with a clear message.
  • On a real Keycloak 26.0.8, with consent required and the auth_time mapper of the basic scope: log in, revoke the consent of the client (Keycloak sends a logout token for the sid and keeps the SSO session), and log in again by SSO 6 s later. The auth_time version answered 400 and left no session. This version answers 302 with the same sid. A scratch spec ran this, and it is not in the PR.
  • pnpm test:e2e:stack on Keycloak: 11 passed, and 3 skipped for features that this stack does not turn on (DPoP, a refresh on each call).
  • .agents/skills/bff-session-lifecycle/model/check.sh prints only ok. BackChannel.cfg holds every rule in 82,555 states, where before BackChannelLogoutEndsSessions broke. BackChannelNoLock.cfg and BackChannelNoDeadline.cfg each remove one part of the fix, and that rule breaks in each.

@pdevito3

Copy link
Copy Markdown
Owner Author

Review findings that stay open

Two review rounds ran on this branch. These findings stay open, each with its reason.

  • Medium, round 2: a code issued before the logout and redeemed more than 5 s after it gets a live row, if the IdP redeems codes of an ended session. Kept as a documented precondition (spec 3.1, and the leave-out list of the model). Reasons:
    • Keycloak 26.0.8 refuses that exchange ("User session not found" / "Session not active" in AuthorizationCodeGrantType). Authentik binds each code to its AuthenticatedSession with on_delete=CASCADE. These are the providers of the stack that send logout tokens. Duende is not checked.
    • The fix that the review offers adds a rule on the challenge time. That rule compares the clocks of the BFF and the IdP, or of BFF instances with a new column, and it refuses each login for the length of its margin after a consent revoke. The review also offered the documented precondition as the alternative.
    • Decision for a maintainer: keep the precondition, or add the challenge-time rule and accept its refusal window.
  • L1 (Low, accepted). A login that begins before the deploy and ends after it has no deadline in its state. Its callback gets 400 one time, and the user logs in again. If OnTicketReceived found an old row of the browser, it already deleted it. Reason: the BFF fails closed. A login with no deadline could outlive the record that ends it.
  • Info, round 2 (documented). During a rolling deploy, an instance with the old code writes the row of a login with no lock and no read of the records, until the rollout ends.
  • I1 (Info, documented). The 5 min clock skew in the record lifetime covers a difference of up to 2 min between any two BFF instances, because four clocks meet in the rule. Instances that sync with NTP differ by milliseconds.
  • Info, round 2 (accepted). A logout and a new login of the same sid within 5 s refuse that login one time, for example a consent revoke and an immediate login.
  • Declined: a named method for the verifySucceeded query of CreateAsync. It has one caller, and its tag bff_sessions.created names it in the logs.

Out of scope, seen during the checks:

  • A refused or failed callback shows the browser a raw JSON problem ({"title":"Invalid authorization response","status":400,...}), not a page of the SPA. This is the design of spec 3.2 for each failed callback, and this PR only adds one more cause.
  • The comment of endKeycloakSession in frontend/e2e/auth-flows.spec.ts says that the BFF revokes the refresh token when it gets a back-channel logout token. It does not (BackChannelLogoutEndpoint.cs, the comment above the row delete). The comment came to main in feat(frontend): send a visitor with no session to the login #414.

@pdevito3

Copy link
Copy Markdown
Owner Author

Maintainer decision on the open medium: keep the spec precondition (an IdP must refuse a code for a session that it ended). Keycloak and Authentik obey it. No second clock rule in this PR.

Base automatically changed from fix/bff-lifecycle-exits to main November 15, 2026 18:12
… one-transaction back-channel logout

The model comes from fv/bff-session. It now describes the code at
b43c777: the jti and the session deletes commit in one transaction, so
JtiInSameTransaction, ForgetAsync, and BackChannelFixed.cfg are gone, and
G2 holds. The line references name the code at that commit.

check.sh prints only ok lines. G1 still breaks on BackChannel.cfg: a
back-channel logout that comes before the login row commits is lost.
…ore its row

A back-channel logout that came after the code exchange and before the
login wrote its row found no row, and the login then created one that
stayed signed in.

The replay cache row now keeps the sid, the sub, and the iat of the
token. The login transaction takes IdpSessionLock, reads these records,
and refuses a login of the same IdP session if a record was issued at
or after the iat of its ID token, less 5 s for the clocks of the IdP.
The auth_time is not used: an SSO login keeps the auth_time of the
first authentication, so after an IdP that keeps the session past its
logout token (the Keycloak consent revoke), each SSO login would fail
until the record expires.

The logout takes the same lock before the find. A login also fails at
its deadline, the challenge plus RemoteAuthenticationTimeout, and a
record lives at least until the last such deadline, so the cleanup
never deletes a record that a login in flight needs. A refused login
gets the 400 problem of a failed callback.

The bff-session-lifecycle model describes the fix. BackChannel.cfg holds
every rule, and two new configs show that the lock and the deadline are
each needed.
@pdevito3
pdevito3 force-pushed the fix/bff-logout-after-login branch from 09761a6 to 2fb490f Compare November 15, 2026 18:19
@pdevito3
pdevito3 merged commit a1637f8 into main Nov 15, 2026
23 checks passed
@pdevito3
pdevito3 deleted the fix/bff-logout-after-login branch November 15, 2026 18:43
pdevito3 added a commit that referenced this pull request Nov 16, 2026
…sh commits on main (#533)

## Why

The formal verification skills must stay true to the code on main. The
three TLA+ skills recorded sync commits from their PR branches. A squash
merge left those commits off main, so the `git log <sync>..HEAD` check
in each skill named a commit that main does not have.

## What changed

- `bff-session-lifecycle` now syncs to `a1637f8a` (#525).
`object-storage-lifecycle` syncs to `d4c3fef7` (#526).
`membership-lifecycle` syncs to `adeb4db0` (#528).
- The skills cited other branch commits as history. Each of those now
names the main commit that holds the same code, which is #519 or #521.

## Scope

- No change to a model, a config, or `check.sh`. The covered code that
main changed after each branch point does not change what the models
describe.
- No product code changes.

## Blast Radius

Only skill text changes, so the app is not affected. An agent that uses
these skills now compares against commits that exist on main.

## Verification

- `bff-session-lifecycle/model/check.sh` printed only `ok` lines.
`object-storage-lifecycle/check.sh` kept every config at its baseline.
`membership-lifecycle/check.sh` passed all 4 configs.
- `scripts/remove-examples.cs` and the example-name grep of
`without-examples.cs` passed on a copy of this branch. The full script
stopped at its Docker check because Docker Desktop did not start.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant